<?php

namespace app\api\controller;

use app\facade\Redis;
use rsa\Rsa;
use app\models\{Wechat, User as Users, Address, Message, Region, AreaPrice, CateSons, GarbageCate, Riderlist, Order, Orderlog, PartnerApply, RiderStreet, Payment};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function sonsdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new AreaPrice())->where(['id' => $id])->find();
        if (!empty($list)) {
            $list['details'] = json_decode($list['details'], true)
            ;
        }
        $this->result($list, 0, '获取成功');
    }

    public function info()
    {
        $list = (new Users())->field('openid,token,created,password,updated,pid', true)->where('id', $this->request->user_id)->find();
        $list['total'] = (new Order())->where(['user_id' => $list['id'], 'status' => [4, 5]])->sum('total');
        $list['city_text'] = (new Region())->where(['area_code' => $list['cityid']])->value('name');
        $list['area_text'] = (new Region())->where(['area_code' => $list['areaid']])->value('name');
        $this->result($list, 0, '获取成功');
    }

    public function invita()
    {
        $list = (new Users())->field('id,nickname,logo,created')->where('pid', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['money'] = (new Order())->where(['user_id' => $lists['id'], 'status' => [4, 5]])->sum('total');
        }
        $this->result($list, 0, '获取成功');
    }

    public function setmobile()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'iv.require' => 'IV不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $user = (new Users())->where('id', $this->request->user_id)->find();
        try {
            $decryptedData = $app->encryptor->decryptData($user['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, '操作失败,请删除小程序重新授权');
        }
        if (!empty($decryptedData['phoneNumber'])) {
            $data['mobile'] = $decryptedData['phoneNumber'];
            $res = (new Users())->where('id', $this->request->user_id)->update(['mobile' => $data['mobile']]);
            if ($res) {
                $this->result(['mobile' => $data['mobile']], 0, '授权成功');
            }
        }
        $this->result([], 1, '授权失败');
    }

    public function qrcode()
    {
        $name = 'appcode' . $this->request->user_id . '.png';
        $qcode = url('/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/wechat/";
        if (!file_exists($path . $name)) {
            $user = (new Users())->where('id', $this->request->user_id)->find();
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $rm->save($path, $name);
            }
        }
        $this->result($qcode, 0, '获取成功');
    }

    //微信小程序账号登录|注册
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        $res = $app->auth->session($data['code']);
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        $time = $config['tokenExpireHours'];
        if (!empty($res['unionid']) && !empty($res['session_key'])) {
            $user = (new Users())->where('unionid', $res['unionid'])->find();
            if (!empty($user)) {
                $savearr = [
                    'session_key' => $res['session_key'],
                    'logo' => $decryptedData['avatarUrl'] ?? '',
                    'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? '')
                ];
                (new Users())->where('unionid', $res['unionid'])->update($savearr);
                $token = md5($user['code'] . time());
                $id = $user['id'];
            } else {
                $pid = 0;
                if (!empty($data['invite'])) {
                    $pid = (new Users())->where('code', $data['invite'])->value('id');
                    $pid = $pid ?? 0;
                }
                $savearr = [
                    'session_key' => $res['session_key'],
                    'openid' => $res['openid'] ?? '',
                    'pid' => $pid,
                    'code' => recode(new Users()),
                    'mobile' => $data['mobile'] ?? '',
                    'logo' => $decryptedData['avatarUrl'] ?? '',
                    'unionid' => $res['unionid'],
                    'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? '')
                ];
                try {
                    $id = (new Users())->insertGetId($savearr);
                } catch (\Exception $e) {
                    $this->result([], 1, '登录失败,请重试');
                }
                $token = md5($savearr['code'] . time());
            }
            if ($id) {
                Redis::setex($token, $time, $id);
            } else {
                $this->result([], 1, '登录失败,请重试');
            }
            $this->result(['token' => $token, 'expire' => $time], 0, '登录成功');
        } else {
            $this->result([], 1, '登录失败');
        }
    }

    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'lon' => 'require',
                'lat' => 'require',
                'is_default' => 'require|in:1,2'
            ], [
                'name.require' => '联系人不能为空',
                'mobile.require' => '联系电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '详细地址不能为空',
                'lon.require' => '地址坐标不能为空',
                'lat.require' => '地址坐标不能为空',
                'is_default.require' => '地址类型不能为空',
                'is_default.in' => '地址类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            if (!empty($data['id'])) {
                $list = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
                if (empty($list)) {
                    $this->result([], 1, '地址信息不存在');
                }
            }
            $data['user_id'] = $this->request->user_id;
            $data['area'] = $area['area_code'];
            $data['city'] = $city['area_code'];
            $data['province'] = $province['area_code'];
            Db::startTrans();
            try {
                (new Address())->where('user_id', $this->request->user_id)->update(['is_default' => 1]);
                if (!empty($data['id'])) {
                    (new Address())->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    (new Address())->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $list = (new Address())->where('user_id', $this->request->user_id)->order('is_default desc')->select();
            $key = '6YGBZ-3CQWP-MAQDB-LNPC4-RZZ27-FYFM4';
            foreach ($list as $lists) {
                $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
                $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
                $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
                $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function address_detail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Address())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (!empty($list)) {
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
        } else {
            $this->result([], 1, '获取失败');
        }
        $this->result($list, 0, '获取成功');
    }

    public function getstreet()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Region())->where(['area_code' =>  $id, 'level' => 4])->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function garbagecate()
    {
        $list = (new GarbageCate())->field('id,name,icon,url,msgs')->select();
        $this->result($list, 0, '获取成功');
    }

    public function areaprice()
    {
        $areaid = $this->request->get('areaid/d', 0);
        $cat = $this->request->get('cat/d', 0);
        //通过街道获取区域id
        $areatop = (new Region())->where('id', $areaid)->value('area_code');
        $where = [
            'streetid' => $areaid,
            'cate' => $cat
        ];
        $whereOr = [
            'areaid' => $areatop,
            'streetid' => 0,
            'cate' => $cat
        ];
        $whereor2 = [
            'areaid' => 0,
            'streetid' => 0,
            'cate' => $cat
        ];
        $list = (new CateSons())->order('sort desc')->where($where)->whereOr(function ($query) use ($whereOr) {
            $query->where($whereOr);
        })->whereOr(function ($query1) use ($whereor2) {
            $query1->where($whereor2);
        })->field('cate,created', true)->select();
        foreach ($list as $lists) {
            $sons = [
                'areaid' => $areatop,
                'streetid' => 0,
                'catsonsid' => $lists['id']
            ];
            $sons2 = [
                'streetid' => $areaid,
                'catsonsid' => $lists['id']
            ];
            $lists['spec'] = (new AreaPrice())->where($sons)->whereOr(function ($query3) use ($sons2) {
                $query3->where($sons2);
            })->field('id,names,price,descs,details,unit,images')->select();
            foreach ($lists['spec'] as $spec) {
                $spec['details'] = json_decode($spec['details'], true);
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function recser()
    {
        $areaid = $this->request->get('areaid/d', 0);
        $list = (new AreaPrice())->field('id,names,price,descs,details,unit,images')->limit(6)->order('sort desc')->where('streetid', $areaid)->select();
        foreach ($list as $lists) {
            $lists['details'] = json_decode($lists['details'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function order()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'addressid' => 'require',
                'appointment' => 'require',
                'data' => 'require',
            ], [
                'addressid.require' => '地址id不能为空',
                'appointment.require' => '预约时间不能为空',
                'data.require' => '数据不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!strtotime($data['appointment'])) {
                $this->result([], 1, '时间格式错误');
            }
            $data['appointment'] = date('Y-m-d H:i:s', strtotime($data['appointment']));
            if ($data['appointment'] < date('Y-m-d H:i:s', time())) {
                $this->result([], 1, '预约时间不能低于当前时间');
            }
            $data['data'] = json_decode($data['data'], true);
            if (empty($data['data'])) {
                $this->result([], 1, '数据格式错误');
            }
            //判断地址是否正确
            $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
            if (empty($address)) {
                $this->result([], 1, '地址错误');
            }
            //判断当前区域是否有家政
            $RiderStreet = (new RiderStreet())->where(['street' => $address['street'], 'status' => 2])->column('riderid');
            if (count($RiderStreet) <= 0) {
                $this->result([], 1, '地址区域没有家政人员');
            }
            $RiderList = (new RiderList())->where(['id' => $RiderStreet, 'status' => 1])->column('user_id');
            if (count($RiderList) <= 0) {
                $this->result([], 1, '地址区域家政人员繁忙，请稍后再下单');
            }
            $ordersn = time() . rand(11111, 99999);
            $orderdata = [
                'user_id' => $this->request->user_id,
                'appointment' => $data['appointment'],
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'city' =>  $address['city'],
                'area' =>  $address['area'],
                'street' =>  $address['street'],
                'address' =>  $address['address'],
                'posaddress' => $address['posaddress'] ?? '',
                'lon' =>  $address['lon'],
                'lat' =>  $address['lat'],
                'status' => 1,
                'ordersn' => $ordersn,
                'info' => !empty($data['info']) ? $data['info'] : '',
            ];
            $orderlog = [];
            foreach ($data['data'] as $datas) {
                if (empty($datas['num'])) {
                    $datas['num'] = 0;
                }
                $datas['num'] = (int)$datas['num'];
                if ($datas['num'] < 1) {
                    $this->result([], 1, '数量不能小于1');
                }
                if (empty($datas['id'])) {
                    $this->result([], 1, '数据参数错误');
                }
                $list = (new AreaPrice())->where(['id' => $datas['id'], 'streetid' => $address['street']])->find();
                if (empty($list)) {
                    $list = (new AreaPrice())->where(['id' => $datas['id'], 'areaid' => $address['area']])->find();
                }
                if (empty($list)) {
                    $this->result([], 1, '服务地址与当前定位区域不符，请手动选择定位');
                }
                $orderlog[] = [
                    'ordersn' => $ordersn,
                    'areapriceid' => $list['id'],
                    'money' =>  $list['price'],
                    'number' => $datas['num'],
                    'icon' => $list['images'],
                    'name' => $list['names'],
                    'unit' => $list['unit'],
                ];
            }
            Db::startTrans();
            try {
                (new Order())->allowfield(true)->save($orderdata);
                (new Orderlog())->insertAll($orderlog);
                Db::commit();
            } catch (\Exception $exception) {
                dump($exception->getMessage());
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $data = $this->request->get();
            $validate = new Validate([
                'addressid' => 'require'
            ], [
                'addressid.require' => '地址id不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //判断地址是否正确
            $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
            if (empty($address)) {
                $this->result([], 1, '地址错误');
            }
            //判断当前区域是否有家政
            $RiderStreet = (new RiderStreet())->where(['street' => $address['street'], 'status' => 2])->column('riderid');
            if (count($RiderStreet) <= 0) {
                $this->result([], 1, '地址区域没有人员分配，请后续关注');
            }
            $RiderList = (new RiderList())->where(['id' => $RiderStreet, 'status' => 1])->column('user_id');
            if (count($RiderList) <= 0) {
                $this->result([], 1, '地址区域人员繁忙，请稍后再下单');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function orderlist()
    {
        $list = (new Order())->order('id desc');
        $status = $this->request->get('status/d', 0);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->field('id,ordersn,status,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,orders_id,mobile,posaddress')->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
            $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
            $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
            $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,number,areapriceid,money,unit,units,price')->select();
            $lists['total'] = 0;
            if ($lists['status'] == 1 || $lists['status'] == 2) {
                foreach ($lists['orderlog'] as $orderlog) {
                    $lists['total'] += $orderlog['number'] * $orderlog['money'];
                }
            }
            if ($lists['status'] == 3 || $lists['status'] == 4 || $lists['status'] == 5) {
                foreach ($lists['orderlog'] as $orderlog) {
                    $lists['total'] += $orderlog['price'] * $orderlog['units'];
                }
            }
            $lists['order_mobile'] = '';
            if ($lists['orders_id'] > 0) {
                $lists['order_mobile'] = (new Riderlist())->where('id', $lists['orders_id'])->value('mobile');
            }
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待接单';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '已接单';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '待付款';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 5) {
                $lists['status_text'] = '待评价';
            }
            if ($lists['status'] == 6) {
                $lists['status_text'] = '已取消';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function ordercancel()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id])->find();
        if (empty($list)) {
            $this->result([], 1, '订单数据不存在');
        }
        if ($list['status'] != 1) {
            $this->result([], 1, '订单不可取消');
        }
        $res = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 6]);
        if ($res) {
            $this->result([], 1, '取消成功');
        }
        $this->result([], 1, '取消失败，请重试');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id])
            ->field('id,ordersn,status,orders_id,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,mobile,riderlon,riderlat,posaddress,star,content')->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $rider = (new Riderlist())->where('id', $lists['orders_id'])->find();
        $lists['riderlon'] = $rider['riderlon'];
        $lists['riderlat'] = $rider['riderlat'];
        $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
        $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
        $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
        $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
        $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,number,areapriceid,money,units,unit,price')->select();
        $lists['total'] = 0;
        if ($lists['status'] == 1 || $lists['status'] == 2) {
            foreach ($lists['orderlog'] as $orderlog) {
                $lists['total'] += $orderlog['number'] * $orderlog['money'];
            }
        }
        if ($lists['status'] == 3 || $lists['status'] == 4 || $lists['status'] == 5) {
            foreach ($lists['orderlog'] as $orderlog) {
                $lists['total'] += $orderlog['price'] * $orderlog['units'];
            }
        }
        if ($lists['orders_id'] > 0) {
            $lists['order_mobile'] = (new Riderlist())->where('id', $lists['orders_id'])->value('mobile');
        } else {
            $lists['order_mobile'] = '';
        }
        if ($lists['status'] == 1) {
            $lists['status_text'] = '待接单';
        }
        if ($lists['status'] == 2) {
            $lists['status_text'] = '已接单';
        }
        if ($lists['status'] == 3) {
            $lists['status_text'] = '待付款';
        }
        if ($lists['status'] == 4) {
            $lists['status_text'] = '已完成';
        }
        if ($lists['status'] == 5) {
            $lists['status_text'] = '待评价';
        }
        if ($lists['status'] == 6) {
            $lists['status_text'] = '已取消';
        }
        $this->result($lists, 0, '获取成功');
    }

    public function partnerApply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'type' => 'require|in:1,2',
                'mobile' => 'require',
                'info' => 'require'
            ], [
                'province.require' => '省份ID不能为空',
                'city.require' => '城市ID不能为空',
                'area.require' => '区域ID不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型错误',
                'mobile.require' => '手机不能为空',
                'info.require' => '备注不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $user = (new Users())->where('id', $this->request->user_id)->find();
            if ($user['cityid'] ||  $user['areaid']) {
                $this->result([], 1, '您已经是合伙人，无法重复申请');
            }
            //判断是否存在待审核信息
            $apply = (new PartnerApply())->where(['status' => 1, 'user_id' => $this->request->user_id])->find();
            if (!empty($apply)) {
                $this->result([], 1, '您有待审核的申请，请等待申请完成');
            }
            //判断区域是否已存在
            if ($data['type'] == 1) {
                $cityuser = (new Users())->where('cityid', $data['city'])->find();
                if (!empty($cityuser)) {
                    $this->result([], 1, '该城市已有合伙人');
                }
            }
            $areauser = (new Users())->where('areaid', $data['area'])->find();
            if (!empty($areauser)) {
                $this->result([], 1, '该区域已有合伙人');
            }
            //查省市区是否存在
            $province = (new Region())->where(['area_code' => $data['province'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $city = (new Region())->where(['area_code' => $data['city'], 'level' => 2, 'parent_id' => $province['id']])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $area = (new Region())->where(['area_code' => $data['area'], 'level' => 3, 'parent_id' => $city['id']])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['user_id'] = $this->request->user_id;
            $res = (new PartnerApply())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '申请成功，等待审核');
            }
            $this->result([], 1, '申请失败，请重试');
        } else {
            $list = (new PartnerApply())->field('user_id', true)->where(['status' => 1, 'user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
                $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
                $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function RiderApply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'password' => 'require',
                'name' => 'require',
                'cards' => 'require',
                'positive' => 'require',
                'negative' => 'require',
                'street' => 'require'
            ], [
                'mobile.require' => '手机号不能为空',
                'password.require' => '密码不能为空',
                'name.require' => '名称不能为空',
                'cards.require' => '身份证号不能为空',
                'positive.require' => '身份证正面不能为空',
                'negative.require' => '身份证反面不能为空',
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '联系电话格式不正确');
            }
            $data['password'] = md5(md5($data['password']));
            //查省市区是否存在
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $data['area'] = $area['area_code'] ?? 0;
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $data['city'] = $city['area_code'] ?? 0;
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $data['province'] = $province['area_code'] ?? 0;
            $riderList = (new RiderList())->where(['user_id' => $this->request->user_id])->find();
            if (!empty($riderList)) {
                $Ridercount = (new RiderStreet())->where(['riderid' => $riderList['id'], 'status' => 2])->count();
                if ($Ridercount > 0) {
                    $this->result([], 1, '您已申请成功，如需继续申请请登录员工入口申请');
                }
                $riderid = $riderList['id'];
                $RiderStreet = (new RiderStreet())->where(['riderid' => $riderList['id']])->find();
                if (!empty($RiderStreet) && $RiderStreet['status'] == 1 && $RiderStreet['street'] != $street['id']) {
                    $this->result([], 0, '不可以同时申请多个街道，请等待其它街道审核完成');
                }
                if (!empty($RiderStreet) && $RiderStreet['status'] == 2 && $RiderStreet['street'] == $street['id']) {
                    $this->result([], 0, '您已是该区域员工，无须重复申请');
                }
            }
            $save = [
                'user_id' => $this->request->user_id,
                'mobile' => $data['mobile'],
                'password' => $data['password'],
                'name' => $data['name'],
                'cards' => $data['cards'],
                'positive' => $data['positive'],
                'negative' => $data['negative']
            ];
            Db::startTrans();
            try {
                if (!empty($riderList)) {
                    (new RiderList())->allowfield(true)->save($save, ['id' => $riderList['id']]);
                } else {
                    $riderid = (new RiderList())->insertGetId($save);
                }
                if (!empty($RiderStreet)) {
                    (new RiderStreet())->where('id', $RiderStreet['id'])->update([
                        'riderid' => $riderid,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                } else {
                    (new RiderStreet())->insert([
                        'riderid' => $riderid,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new RiderList())->field('user_id,password', true)->where(['user_id' => $this->request->user_id])->find();
            if (!empty($list)) {
                $riderstreet = (new RiderStreet())->where(['riderid' => $list['id']])->find();
                if (!empty($riderstreet)) {
                    $list['province'] = $riderstreet['provinceid'];
                    $list['city'] = $riderstreet['cityid'];
                    $list['area'] = $riderstreet['areaid'];
                    $list['street'] = $riderstreet['street'];
                    $list['province_text'] = (new Region())->where(['area_code' => $riderstreet['provinceid']])->value('name');
                    $list['city_text'] = (new Region())->where(['area_code' => $riderstreet['cityid']])->value('name');
                    $list['area_text'] = (new Region())->where(['area_code' => $riderstreet['areaid']])->value('name');
                    $list['street_text'] = (new Region())->where(['id' => $riderstreet['street']])->value('name');
                    $list['status'] = $riderstreet['status'];
                }
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'mobile' => 'require',
                'messtype' => 'require'
            ], [
                'message.require' => '反馈信息不能为空',
                'mobile.require' => '联系电话不能为空',
                'messtype.require' => '反馈类型不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['type'] = 1;
            $data['user_id'] = $this->request->user_id;
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->user_id, 'type' => 1])
                ->field('message,reply,created')
                ->paginate(20, false, ['query' => $this->request->param()]);
            $this->result($list, 0, '查询完成');
        }
    }

    //订单评价
    public function evalorder()
    {
        //查询订单是否存在
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'star' => 'require|in:1,2,3,4,5',
            'content' => 'require'
        ], [
            'id.require' => '订单id不能为空',
            'star.require' => '评价星级不能为空',
            'star.in' => '评价星级范围在1-5星',
            'content.require' => '评价内容不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $lists = (new Order())->where(['id' => $data['id'], 'user_id' => $this->request->user_id, 'status' => 5])->find();
        if (empty($lists)) {
            $this->result([], 1, '订单不存在或当前状态无法评价');
        }
        $res = (new Order())->where('id', $lists['id'])->update(['status' => 4, 'star' => $data['star'], 'content' => $data['content']]);
        if ($res) {
            $this->result([], 0, '评价成功');
        }
        $this->result([], 1, '评价失败');
    }

    //订单付款、
    public function payorder()
    {
        //查询订单是否存在
        $id = $this->request->get('id/d', 0);
        $lists = (new Order())->where(['id' => $id, 'user_id' => $this->request->user_id, 'status' => 3])->find();
        if (empty($lists)) {
            $this->result([], 1, '订单不存在或当前状态无法付款');
        }
        if ($lists['total'] < 0.01) {
            $this->result([], 1, '订单金额不足0.01,请选择其它支付方式');
        }
        $payment = [
            'pay_title' => $lists['ordersn'] . '家政订单',
            'payment_id' =>  $lists['ordersn'] . rand(1000, 9999),
            'money' => $lists['total'],
            'ip' => $this->request->ip(),
            'user_id' => $lists['user_id'],
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        $list = (new Wechat())->pay($payment);
        if ($list['status'] == true) {
            //插入支付记录
            (new Payment())->save([
                'paymentid' => $payment['payment_id'],
                'orderid' => $lists['id'],
                'money' => $payment['money']
            ]);
        }
        $this->result($list, 0, '获取成功');
    }
}
